package com.example.service.impl;

import com.example.entity.User;
import com.example.mapper.UserMapper;
import com.example.service.UserService;
import com.example.Util.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public String wechatLogin(String openid) {
        User user = userMapper.selectByOpenid(openid);
        // 新用户自动注册
        if (user == null) {
            user = new User();
            user.setOpenid(openid);
            user.setNickname("微信用户");
            user.setAvatar("");
            userMapper.insert(user);
        }
        return jwtUtils.generateToken(openid);
    }

    @Override
    public void updateUserInfoByOpenid(String openid, String nickname, String avatar) {
        User user = userMapper.selectByOpenid(openid);
        if (user != null) {
            user.setNickname(nickname);
            user.setAvatar(avatar);
            userMapper.update(user);
        }
    }

    @Override
    public User getUserInfo(Integer userId) {
        return userMapper.selectById(userId);
    }

    @Override
    public void updateUserInfo(User user) {
        userMapper.update(user);
    }
}